const http = require('../utils/http');
const moment = require('../libs/moment');
const { Calc, Report, BodyAgeReport, BodyShapeReport } = require('../report/index');
const DateUtils = require('../utils/DateUtils')

const { dataValid } = require('../utils/util.js')
const theme = require("../theme.config.js")

const APP_TYPE = "xcx_third"
var { hexMD5 } = require('../utils/md5');

class Measure {

  uploadScaleData({ device, scaleParam, bodyParams, hasResistance, needPrepare, invalid_id, APP_ID, SECRET, version, calc_type }) {
      const { height, gender, birthday, waist, hip, person_body_shape, person_goal } = bodyParams
      const bodyParamsObject = {
        Body_Height: height.toString(),
        User_Age: DateUtils.getAge(birthday, new moment()),
        User_Gender: gender.toString(),
        birthday
      }
      if (!theme.sportStatus) {
        if (person_body_shape != undefined && person_goal != undefined) {
          bodyParamsObject.Person_Body_Shape = parseInt(person_body_shape)
          bodyParamsObject.Person_Goal = parseInt(person_goal)
        }
      }
      let manufacturer = scaleParam.manufacturer.toUpperCase()
      let app_type = scaleParam.app_type

      delete scaleParam.manufacturer
      delete scaleParam.app_type

      const timestamp = moment().unix()
      const bodyParamString = JSON.stringify(bodyParamsObject)
      const scaleParamString = JSON.stringify(scaleParam)


      const measure_time = new moment()
      const local_updated_at = measure_time.format("YYYY-MM-DD HH:mm:ss")

      const paramData = {
        app_id: APP_ID,
        body_param: bodyParamString,
        scale_param: scaleParamString,
        app_type: APP_TYPE,
        local_name: device && device.localName,
        manufacturer,
        local_updated_at,
        simple: true,
        improve_flag: hasResistance ? 1 : 0,
        on_flag: 1,
        timestamp,
      }

      if (invalid_id) {
        paramData.invalid_id = invalid_id
      }

      if (version != undefined) {
        paramData.version = parseInt(version)
      }
      if (calc_type != undefined) {
        paramData.calc_type = parseInt(calc_type)
      }

      return http.doPost(theme.url.scaleData, paramData)
        .then(data => {
          const { resultData, code, invalid_id } = data
          if (code == "200") {
            resultData.birthday = birthday
            resultData.waist = waist
            resultData.hip = hip
            if (needPrepare) {
              return this.prepareData(resultData)
            } else {
              return resultData
            }
          } else {
            throw { code, invalid_id }
          }
        })
    }

    uploadData({ device, scaleString, bodyParams, hasResistance, needPrepare, invalid_id, APP_ID, SECRET, version}) {
        const { height, gender, birthday, waist, hip, person_body_shape, person_goal } = bodyParams
        const bodyParamsObject = {
            Body_Height: height.toString(),
            User_Age: DateUtils.getAge(birthday, new moment()),
            User_Gender: gender.toString(),
            birthday
        };
        if (person_body_shape != undefined && person_goal != undefined) {
          bodyParamsObject.Person_Body_Shape = person_body_shape
          bodyParamsObject.Person_Goal = person_goal
        }
        const timestamp = moment().unix()
        const bodyParamString = JSON.stringify(bodyParamsObject)
        
        let toSignString = APP_ID + scaleString + bodyParamString + timestamp + SECRET
        
        const sign = hexMD5(toSignString)

        const measure_time = new moment()
        const local_updated_at = measure_time.format("YYYY-MM-DD HH:mm:ss")

        const paramData = {
            app_id: APP_ID,
            body_param: bodyParamString,
            scale: scaleString,
            sign_type: "MD5",
            local_name: device.localName,
            manufacturer: device.manufacturer,
            sign,
            app_type: APP_TYPE,
            local_updated_at,
            simple: true,
            //improve_flag: hasResistance ? 1 : 0,
            timestamp,
            on_flag: 1,
        }

        if (version != undefined) {
          paramData.version = version
        }

        if (invalid_id) {
          paramData.invalid_id = invalid_id
        }

        return http.doPost(theme.url.calcData, paramData)
            .then(data => {
                const { resultData,code,invalid_id } = data
              
                if(code == "200"){
                  resultData.birthday = birthday
                  resultData.height = height
                  resultData.gender = gender
                  resultData.waist = waist
                  resultData.hip = hip
                  if (needPrepare) {
                      return this.prepareData(resultData)
                  } else {
                      return resultData
                  }
                }else{
                  throw {code,invalid_id}
                }
            })

    }

    prepareData(data, params = {}) {

        const measure = {}
        measure.userId = data.user_id
        measure.birthday = data.birthday
        measure.gender = data.gender
        measure.height = data.height
        measure.waist = data.waistline
        measure.hip = data.hip

        measure.weight = parseFloat(data.weight.toFixed(2))
        measure.bmi = parseFloat(data.bmi.toFixed(1))
        measure.bodyfat = parseFloat(data.bodyfat.toFixed(1))

        if (dataValid(data)) {

            measure.water = parseFloat(data.water.toFixed(1))
            measure.subfat = parseFloat(data.subfat.toFixed(1))
            measure.muscleMass = parseFloat(data.sinew.toFixed(2))
            measure.muscle = parseFloat(data.muscle.toFixed(1))
            measure.bone = parseFloat((data.bone / 10).toFixed(2))
            measure.bmr = parseFloat((data.bmr * 10).toFixed())
            measure.protein = parseFloat(data.protein.toFixed(1))
            measure.lbm = parseFloat(data.fat_free_weight.toFixed(2))
            measure.visfat = parseInt(data.visfat.toFixed(0))

            measure.heartRate = data.heart_rate ? parseInt(data.heart_rate.toFixed(0)) : 0
            measure.heartIndex = data.cardiac_index ? parseInt(data.cardiac_index.toFixed(0)) : 0

            measure.score = data.score

            measure.bodyAge = data.bodyage

            measure.bodyShape = data.body_shape

        } else {
            measure.water = 0
            measure.subfat = 0
            measure.muscleMass = 0
            measure.muscle = 0
            measure.bone = 0
            measure.bmr = 0
            measure.protein = 0
            measure.lbm = 0
            measure.visfat = 0

            measure.score = 0

            measure.bodyAge = 0

            measure.bodyShape = 0

            measure.heartRate = 0

        }

        measure.time = new moment(data.local_updated_at, "YYYY-MM-DD HH:mm:ss")
        measure.measure_time = measure.time

        measure.origin = data

        return new Report(measure, params)
    }

}

module.exports = new Measure()